package com.gitee.wsl.scheduler

import com.gitee.wsl.concurrent.collections.ConcurrentMutableMap
import com.gitee.wsl.scheduler.task.SchedulerTask
import kotlinx.atomicfu.atomic

interface TaskRepository {

    val parent:TaskRepository?

    val runTasks: MutableCollection<SchedulerTask>
        get() = tasks.values

    val runTasksSize: Int
        get() = tasks.size


    fun nextId():Int

    /**
     * A thread-safe map that holds all the registered tasks with their unique IDs.
     */
    val tasks: MutableMap<Int, SchedulerTask>

    /**
     * Registers a task by adding it to the tasks' map.
     *
     * @param task The task to register.
     */
    fun registerTask(task: SchedulerTask) {
        tasks[task.id] = task
    }

    /**
     * Unregisters a task by removing it from the tasks' map.
     *
     * @param taskId The ID of the task to unregister.
     */
    fun unregisterTask(taskId: Int) {
        tasks.remove(taskId)?.cancel()
    }


    fun cancelAllTasks() {
        tasks.values.forEach(SchedulerTask::cancel)
        tasks.clear()
    }
}

internal class MemoryTaskRepository(
    override val parent:TaskRepository? = null,
):TaskRepository{

    val tasksWas = atomic(0)

    override fun nextId(): Int = tasksWas.incrementAndGet()

    override val tasks: MutableMap<Int, SchedulerTask> = ConcurrentMutableMap()

    companion object{
        val DEFAULT = MemoryTaskRepository()
    }
}